<?php
namespace Home\Controller;
use Server\PayService;
use Think\Controller;
class CartController extends BaseController {
    public function __construct() {
        parent::__construct();
        $this->assign('act','cart');
    }
    public function index(){
        $this->changeCartPrice();
        $mod = M('cart');
        $user_id = session('user_id');
        $store = $mod->where(array('user_id'=>$user_id))->group('store_id')->field('store_id')->select();
        $b_mod = M('business');
        foreach((array)$store as $k=>$v){
            $store[$k]['store_name'] = $b_mod->where(array('id'=>$v['store_id']))->getField('store_name');
            $store[$k]['cart_list'] = $mod->alias('as a')
                ->join('left join '.C('DB_PREFIX').'goods as b on b.id=a.goods_id')
                ->join('left join '.C('DB_PREFIX').'goods_store_spec as c on c.id=a.spec_id')
                ->field('a.id,b.id as goods_id,a.spec_id,b.goods_name,b.thumb,b.keywords,a.goods_price as spec_price,c.spec_name,a.goods_number')
                ->where(array('a.user_id'=>$user_id,'a.store_id'=>$v['store_id']))
                ->select();
        }
        $this->assign('store',$store);
        if(count($store)){
            $this->display();
        }else {
            $this->display('empty');
        }
    }
    //确认订单
    public function confirm_order(){
        $cart_id = I('cart_id')?rtrim(I('cart_id'),','):'';
        $mod = M('cart');
        $user_id = session('user_id');
        $store = $mod->where(array('user_id'=>$user_id,'id'=>array('in',$cart_id)))->group('store_id')->field('store_id')->select();
        if(!count($store)){
            $this->redirect('Home/Cart/index');
        }
        $b_mod = M('business');
        foreach((array)$store as $k=>$v){
            $store[$k]['store_name'] = $b_mod->where(array('id'=>$v['store_id']))->getField('store_name');
            $store[$k]['cart_list'] = $mod->alias('as a')
                ->join('left join '.C('DB_PREFIX').'goods as b on b.id=a.goods_id')
                ->join('left join '.C('DB_PREFIX').'goods_store_spec as c on c.id=a.spec_id')
                ->field('a.id,b.id as goods_id,a.spec_id,b.goods_name,b.thumb,b.keywords,a.goods_price as spec_price,c.spec_name,a.goods_number')
                ->where(array('a.user_id'=>$user_id,'a.store_id'=>$v['store_id'],'a.id'=>array('in',$cart_id)))
                ->select();
        }
        $this->assign('store',$store);
        $price = $mod->where(array('id'=>array('in',$cart_id)))->sum('goods_price*goods_number');
        //判断是否有促销活动
        $pro_price = $this->check_pro_price($cart_id);
        $this->assign('price',$price);
        $this->assign('count_price',number_format($price-$pro_price,2));
        //获取配送范围
        $get_ship = M('config')->where(array('name'=>'delivery'))->getField('value');
        //获取可用范围内的地址
        $address = M('users_address')->where(array('user_id'=>$user_id,'infocode'=>array('elt',intval($get_ship))))->order('is_default desc')->select();
        $scope_mod = M('goods_delivery');
        foreach((array)$address as $k=>$v){
            $scope_price = $scope_mod->where('start_scope<'.$v['infocode'] .' and end_scope>'.$v['infocode'])->getField('price');
            $address[$k]['scope_price'] = $scope_price?number_format($scope_price,2):'0.00';
        }
		$this->assign('address',$address);
        $this->assign('pro_price',number_format($pro_price,2));
        $this->assign('price',$price);
        $this->assign('count_price',number_format($price-$pro_price,2));
        $this->assign('scope_price',$address[0]['scope_price']);
        $this->assign('cart_id',$cart_id);
        //检测可用的优惠券
        $coupon_mod = M('users_coupon');
        $time = time();
        $cou_price = $mod->where(array('pro_id'=>'0','id'=>array('in',$cart_id)))->sum('goods_price*goods_number');
        $coupon_list = $coupon_mod->alias('as a')
            ->join('left join '.C('DB_PREFIX').'goods_coupon as b on b.id=a.cou_id')
            ->where(array('a.user_id'=>$user_id,'a.order_id'=>0,'b.start_time'=>array('lt',$time),'b.end_time'=>array('gt',$time),'b.use_price'=>array('elt',$cou_price)))
            ->field('b.id,b.title,b.coupon_price,b.end_time')
            ->select();
        $this->assign('coupon_list',$coupon_list);
        $this->assign('coupon_number',count($coupon_list));
        $this->display();
    }
    //提交订单
    public function pay_order(){
        $mod = M('cart');
        $order_mod = M('orders');
        $order_goods_mod = M('orders_goods');
        $user_id = session('user_id');
        $coupon_id = I('coupon_id')?rtrim(I('coupon_id'),','):'';
        $address_id = I('address_id')?I('address_id'):'';
        $cart_id = I('cart_id')?rtrim(I('cart_id'),','):'';
        $pay_type = I('pay_type')?rtrim(I('pay_type'),','):'微信支付';
        $order_remark = I('order_remark')?I('order_remark'):'';
        $store = $mod->where(array('user_id'=>$user_id,'id'=>array('in',$cart_id)))->group('store_id')->field('store_id')->select();
        if(!$store[0]['store_id']){
			exit(json_encode(array('code' => 100,'msg' =>'该订单已不存在')));
		}
		$price = $mod->where(array('id'=>array('in',$cart_id)))->sum('goods_price*goods_number');
        $address = M('users_address')->where(array('user_id'=>$user_id,'id'=>$address_id))->find();
		$scope_price = M('goods_delivery')->where('start_scope<'.$address['infocode'] .' and end_scope>'.$address['infocode'])->getField('price');
        $scope_price = $scope_price>0?$scope_price:0;
        $order_sn = order_sn();
        $time = time();
        $pro_price = $this->check_pro_price($cart_id);
        //验证优惠券
        $coupon_price = 0;
        if($coupon_id){
            $coupon_price = M('users_coupon')
                ->alias('as a')->join('left join '.C('DB_PREFIX').'goods_coupon as b on b.id=a.cou_id')
                ->where(array('a.cou_id'=>$coupon_id,'a.user_id'=>$user_id))
                ->getField('b.coupon_price');
            if(!$coupon_price){
                $coupon_price = 0;
                $coupon_id = 0;
            }
        }
        //判断支付密码是否正确与余额是否不足
        $u_mod = M('users');
        if($pay_type=='余额支付'){
            $count_price = $price-$coupon_price+$coupon_price-$pro_price;
            $md_pwd = md5(md5(i('pwd')).C('DB_DEVE'));
            $pwd = M('users_pwd')->where(array('user_id'=>$user_id,'password'=>$md_pwd ))->count();
            if(!$pwd){
                exit(json_encode(array('code' => 100,'msg' =>'密码错误')));
            }
            $user_price = $u_mod->where(array('id'=>$user_id))->getField('price');
            if($user_price<$count_price){
                exit(json_encode(array('code' => 100,'msg' => '余额不足，请及时充值。')));
            }
        }
        if(count($store)>1){
            $data = array(
                'user_id' => $user_id,
                'order_sn' => $order_sn,
                'order_price' => $price-$coupon_price+$scope_price-$pro_price,
                'pay_type' => $pay_type,
                'address_id' => $address_id,
                'consignee' => $address['name'],
                'mobile' => $address['mobile'],
                'address' => $address['address_area'] . $address['address'],
                'add_time' => time(),
                'coupon_id'=>$coupon_id,
                'cou_price'=>$coupon_price,
                'shipping_fee'=>$scope_price,
                'pro_price'=>$pro_price,
                'order_remark' => $order_remark
            );
            $result = $order_mod->add($data);
            $coupon_id && M('users_coupon')->where(array('cou_id'=>$coupon_id,'user_id'=>$user_id))->save(array('order_id'=>$result,'user_time'=>time()));
            foreach((array)$store as $k=>$v){
                $cou_price = 0;
                $store_price = $mod->where(array('id'=>array('in',$cart_id),'store_id'=>$v['store_id']))->sum('goods_price*goods_number');
                if($coupon_id) {
                    if (count($store) == $k + 1) {
                        $old_price = $order_mod->where(array('order_sn' => $order_sn,'is_child'=>array('gt',0)))->sum('cou_price');
                        $cou_price = $coupon_price-$old_price;
                    }else{
                        $cou_price = $coupon_price * (floatval($store_price) / floatval($price));
                    }
                }
                $store_pro_price = 0;
                if($pro_price){
                    //判断商家的促销价
                    $pro_all_price = $mod->where(array('id'=>array('in',$cart_id),'pro_id'=>array('gt',0)))->sum('goods_price*goods_number');
                    $pro_one_price = $mod->where(array('id'=>array('in',$cart_id),'store_id'=>$v['store_id'],'pro_id'=>array('gt',0)))->sum('goods_price*goods_number');
                    $store_pro_price = round($pro_price*($pro_one_price/$pro_all_price),2);
                }
                $data = array(
                    'user_id' => $user_id,
                    'store_id'=>$v['store_id'],
                    'order_sn' => $order_sn,
                    'is_child'=>1,
                    'order_price' => $store_price,
                    'pay_type' => $pay_type,
                    'address_id' => $address_id,
                    'consignee' => $address['name'],
                    'mobile' => $address['mobile'],
                    'address' => $address['address_area'] . $address['address'],
                    'add_time' => time(),
                    'coupon_id'=>$coupon_id,
                    'cou_price'=>$cou_price,
                    'pro_price'=>$store_pro_price,
                    'order_remark' => $order_remark
                );
                $order_mod->add($data);
                $cart_list = $mod->where(array('user_id'=>$user_id,'id'=>array('in',$cart_id),'store_id'=>$v['store_id']))->select();
                foreach((array)$cart_list as $kk=>$vv){
                    $cart = array(
                        'order_sn'=>$order_sn,
                        'user_id'=>$user_id,
                        'goods_id'=>$vv['goods_id'],
                        'store_id'=>$v['store_id'],
                        'spec_id'=>$vv['spec_id'],
                        'goods_price'=>$vv['goods_price'],
                        'goods_number'=>$vv['goods_number'],
                        'pro_type'=>$vv['pro_type'],
                        'pro_id'=>$vv['pro_id'],
                    );
                    $order_goods_mod->add($cart);
                }
            }
        }else {
            $data = array(
                'user_id' => $user_id,
                'store_id'=>$store[0]['store_id'],
                'order_sn' => $order_sn,
                'order_price' => $price-$coupon_price+$scope_price-$pro_price,
                'pay_type' => $pay_type,
                'address_id' => $address_id,
                'consignee' => $address['name'],
                'mobile' => $address['mobile'],
                'address' => $address['address_area'] . $address['address'],
                'add_time' => time(),
                'coupon_id'=>$coupon_id,
                'cou_price'=>$coupon_price,
                'pro_price'=>$pro_price,
                'shipping_fee'=>$scope_price,
                'order_remark' => $order_remark
            );
            $result = $order_mod->add($data);
            $coupon_id && M('users_coupon')->where(array('cou_id'=>$coupon_id,'user_id'=>$user_id))->save(array('order_id'=>$result,'user_time'=>time()));
            $cart_list = $mod->where(array('user_id'=>$user_id,'id'=>array('in',$cart_id),'store_id'=>$store[0]['store_id']))->select();
            foreach((array)$cart_list as $k=>$v){
                $cart = array(
                    'order_sn'=>$order_sn,
                    'user_id'=>$user_id,
                    'goods_id'=>$v['goods_id'],
                    'store_id'=>$store[0]['store_id'],
                    'spec_id'=>$v['spec_id'],
                    'goods_price'=>$v['goods_price'],
                    'goods_number'=>$v['goods_number'],
                    'pro_type'=>$v['pro_type'],
                    'pro_id'=>$v['pro_id'],
                );
                $order_goods_mod->add($cart);
            }
        }
        order_log($order_sn,'已提交','您的订单号为'.$order_sn);
        $user_name = M('users')->where(array('id'=>$user_id))->getField('user_name');
        orders_status($user_name,$order_sn,1,0,'');
        $mod->where(array('user_id'=>$user_id,'id'=>array('in',$cart_id)))->delete();
        //余额支付扣款
		$token = '';
		$pay['order_id'] = $result;
        if($pay_type=='余额支付'){
            $r = $u_mod->where(array('id'=>$user_id))->save(array('price'=>($user_price-$count_price)));
            if($r){
                $users_log_mod = M('users_log');
                $users_log_mod->add(array(
                    'user_id'=>$user_id,
                    'type_id'=>1,
                    'price'=>$count_price,
                    'integral'=>0,
                    'add_time'=>time()
                ));
                $this->order_log($order_sn,'待发货','支付成功，商家拣货中');
                orders_status($user_name,$order_sn,2,0,'');
				business_log($order_sn,1);
                $order_mod->where(array('order_sn'=>$order_sn))->save(array('status'=>2,'pay_time'=>time()));
            }
            exit(json_encode(array('code' => 201,'msg' => $store)));
        }else{
			$pay_result = PayService::openidPay($order_sn,$price-$coupon_price+$scope_price-$pro_price,$price,C('ORDER_URL'));
			if($pay_result['code'] === 0) {
				$pay['token'] = $pay_result['data'];
			}
            order_log($order_sn, '待支付', '请你在' . date('Y-m-d H:i:s', $time + 600) . '前完成支付否则订单将自动取消！');
        }
        exit(json_encode(array('code' => 200,'data'=>$pay,'msg' => $store)));
    }
    //订单未支付的提示
    function immediately(){
        $user_id = session('user_id');
        if($user_id) {
            $order_id = i('order_id') ? i('order_id') : '';
            $mod = M('orders');
            $info = $mod->where(array('id' => $order_id, 'user_id' => $user_id))->field('id,status,order_sn,add_time,order_price,pay_type')->find();
            if($info['status']==1){
				$info['add_time'] = date('Y-m-d H:i:s',$info['add_time']+600);
				$this->assign('info', $info);
				$this->display();
			}else{
				$this->redirect('/Home/User/order/');
			}
        }
    }
    //加入购物车
    public function add_cart(){
        $user_id = session('user_id');
        if($user_id) {
            $mod = M('cart');
            $spec_mod = M('goods_store_spec');
            $data = I('post.');
            $type = I('type')?I('type'):2;
            $data['user_id'] = $user_id;
            $data['add_time'] = time();
            $spec_info = $spec_mod->where(array('goods_id'=>$data['goods_id'],'id'=>$data['spec_id']))->field('spec_price,status,is_sold')->find();
            if($spec_info['is_sold']>0){
                exit(json_encode(array('code' => 100, 'msg' => '已售罄')));
            }else if($spec_info['status']<1){
                exit(json_encode(array('code' => 100, 'msg' => '已下架')));
            }
            $data['goods_price'] = $spec_info['spec_price'];
            $cart = $mod->where(array('goods_id'=>$data['goods_id'],'spec_id'=>$data['spec_id'],'store_id'=>$data['store_id']))->field('id,goods_number')->find();
            $time = time();
            if($data['pro_id'] && $data['pro_type']==3){
                $pro_number = M('goods_promotion')->where(array('id'=>$data['pro_id']))->sum('use_number-mall_number');
                $check_number = $mod->where(array('id'=>$cart['id']))->getField('goods_number');
                if($pro_number<$check_number){
                    exit(json_encode(array('code' => 100, 'msg' => '已达到限购数量')));
                }
            }
            $where = 'FIND_IN_SET('.$data['goods_id'].',goods_list) and type_id=1 and start_time<'.$time.' and end_time>'.$time;
            $pro_list = M('goods_promotion')->where($where)->field('id,type_id')->find();
            if($type==1){
                $data['goods_number'] = $cart['goods_number']-$data['goods_number'];
            }else{
                $data['goods_number'] = $cart['goods_number']+$data['goods_number'];
            }
            if($pro_list['id']){
                $data['pro_id'] = $pro_list['id'];
                $data['pro_type'] = $pro_list['type_id'];
            }
            if($cart['id']){
                $where = 'FIND_IN_SET('.$data['goods_id'].',goods_list) and type_id=1 and start_time<'.$time.' and end_time>'.$time;
                $pro_list = M('goods_promotion')->where($where)->field('id,type_id')->find();
                if($type==1){
                    $data['goods_number'] = $cart['goods_number']-$data['goods_number'];
                }else{
                    $data['goods_number'] = $cart['goods_number']+$data['goods_number'];
                }
                if($pro_list['id']){
                    $data['pro_id'] = $pro_list['id'];
                    $data['pro_type'] = $pro_list['type_id'];
                }
                $result = $mod->where(array('id'=>$cart['id']))->save($data);
            }else{
                $result = $mod->add($data);
            }
            $number = $mod->where(array('user_id'=>$user_id))->sum('goods_number');
            if ($result) {
                exit(json_encode(array('code' => 200,'result'=>$number,'msg' => '添加成功')));
            } else {
                exit(json_encode(array('code' => 100, 'msg' => '添加失败')));
            }
        }
    }
    //删除购物车商品
    function del_cart(){
        $user_id = session('user_id');
        if($user_id) {
            $mod = M('cart');
            $data = I('post.');
            $result = $mod->where(array('user_id'=>$user_id,'store_id'=>$data['store_id'],'goods_id'=>$data['goods_id'],'spec_id'=>$data['spec_id']))->delete();
            if ($result) {
                exit(json_encode(array('code' => 200,'msg' => '删除成功')));
            } else {
                exit(json_encode(array('code' => 100, 'msg' => '删除失败')));
            }
        }
    }
    //删除多个购物车商品
    function del_all_cart(){
        $user_id = session('user_id');
        if($user_id) {
            $mod = M('cart');
            $data = I('post.');
            $result = $mod->where(array('user_id'=>$user_id,'id'=>array('in',rtrim($data['cart_id'],','))))->delete();
            if ($result) {
                $number = $mod->where(array('user_id'=>$user_id))->sum('goods_number');
                exit(json_encode(array('code' => 200,'result'=>$number,'msg' => '删除成功')));
            } else {
                exit(json_encode(array('code' => 100, 'msg' => '删除失败')));
            }
        }
    }
    //判断支付密码是否正确
    function pay_type(){
        $user_id = session('user_id');
        $mod = M('users_pwd');
        $pwd = I('pwd')?I('pwd'):'';
        $info = $mod->where(array('user_id'=>$user_id))->field('id,password')->find();
        if($info['id']){
            if($info['password']!=md5(md5($pwd).C('DB_DEVE'))){
                exit(json_encode(array('code' => 100, 'msg' => '密码错误')));
            }else{
                exit(json_encode(array('code' => 200, 'msg' => '密码正确')));
            }
        }else{
            exit(json_encode(array('code' => 100, 'msg' => '密码未设置')));
        }
    }
	//支付回调地址
	function callback(){
        $post = file_get_contents('php://input');
        $post = json_decode($post,true);
        $sign = $post['sign'];
        unset($post['serverName'],$post['serverPort'],$post['scheme'],$post['callbackapiurl'],$post['sign']);
        $data = $post;
        ksort($data);
        $check_sign = PayService::xly_check_data($data,$sign);
        //验签成功
        if($check_sign) {
            $result = PayService::returnHandle($post['data']);
            //确定订单状态为支付成功
            if($result['OrderStatus'] == 1) {
                $order_num = $result['OrderNo'];//订单号码
                $pay_time = $result['PaymentTime'];//支付时间
				$this->success_pay_order($order_num);
            }
        }
//        $result = PayService::weChat_order_select('1500516223');
        /*查询订单接口返回格式
         * ["code"] => int(0)
        ["message"] => string(7) "success"
        ["data"] => array(5) {
            ["OrderNo"] => string(10) "1500516223"
            ["OrderStatus"] => int(1)
            ["Amount"] => float(0.02)
            ["OrderTime"] => string(19) "2017-07-20 10:04:23"
            ["PaymentTime"] => string(19) "2017-07-20 10:04:28"
        }
        */
//        dump($result);
//        file_put_contents('select_order.txt', json_encode($result));
	}
}